<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="160px">
      <el-form-item label="箱码" prop="barcode">
        <el-input
          v-model="queryParams.barcode"
          placeholder="请输入箱码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采购订单编号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入采购订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="批次号" prop="batchNo">
        <el-input
          v-model="queryParams.batchNo"
          placeholder="请输入批次号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="存货编码" prop="inventoryCode">
        <el-input
          v-model="queryParams.inventoryCode"
          placeholder="请输入存货编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供货商编码" prop="supplierCode">
        <el-input
          v-model="queryParams.supplierCode"
          placeholder="请输入供货商编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:barcode:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:barcode:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="barcodeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" width="60" align="center" :index="computeIndex" />
      <el-table-column label="箱码" align="center" prop="barcode" width="160" />
      <!-- <el-table-column label="箱码状态" align="center" prop="barcodeStatus" width="110">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_job_status" :value="scope.row.barcodeStatus"/>
        </template>
      </el-table-column> -->
      <el-table-column label="采购订单编号" align="center" prop="orderNo" width="160" />
      <el-table-column label="批次号" align="center" prop="batchNo" width="140" />
      <el-table-column label="存货编码" align="center" prop="inventoryCode" width="140" />
      <el-table-column label="存货名称" align="center" prop="inventoryName" width="180" />
      <el-table-column label="供应商编码" align="center" prop="supplierCode" width="140" />
      <el-table-column label="供应商名称" align="center" prop="supplierName" width="180" />
      <el-table-column label="装箱数量" align="center" prop="packQuantity" width="120" />
      <el-table-column label="计量单位名称" align="center" prop="unitName" width="140" />
      <el-table-column label="送货编码" align="center" prop="deliveryNoteNo" width="160" />
      <el-table-column label="收料通知单编码" align="center" prop="receiptNoteNo" width="160" />
      <el-table-column label="检验计划编码" align="center" prop="inspectionPlanNo" width="160" />
      <el-table-column label="采购入库编码" align="center" prop="purchaseInNo" width="160" />
      <el-table-column label="是否拒收" align="center" prop="isRejected" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isRejected"/>
        </template>
      </el-table-column>
      <el-table-column label="质检结果" align="center" prop="qualityResult" width="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_job_status" :value="scope.row.qualityResult"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" width="220" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="160">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-printer"
            @click="handlePrint(scope.row)"
          >打印</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:barcode:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改箱码列表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="160px">
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBarcode, getBarcode, delBarcode, addBarcode, updateBarcode } from "@/api/system/barcode"

export default {
  name: "Barcode",
  dicts: ['sys_job_status', 'sys_yes_no'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 箱码列表表格数据
      barcodeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        barcode: null,
        orderNo: null,
        batchNo: null,
        inventoryCode: null,
        supplierCode: null,
        itemId: null,
        receiptNoteNo: null,
        // 默认排序：按创建时间倒序，确保新数据在最上方（使用数据库列名）
        orderByColumn: 'created_time',
        isAsc: 'desc',
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        barcode: [
          { required: true, message: "箱码不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    const itemIdFromRoute = this.$route && this.$route.query && this.$route.query.itemId
    const receiptNoteNoFromRoute = this.$route && this.$route.query && this.$route.query.receiptNoteNo
    if (itemIdFromRoute) {
      this.queryParams.itemId = itemIdFromRoute
    } else {
      this.queryParams.itemId = null
    }
    this.queryParams.receiptNoteNo = receiptNoteNoFromRoute || null
    this.getList()
  },
  // 组件被 keep-alive 缓存后重新激活时，依据路由参数刷新数据
  activated() {
    const itemIdFromRoute = this.$route && this.$route.query && this.$route.query.itemId
    const receiptNoteNoFromRoute = this.$route && this.$route.query && this.$route.query.receiptNoteNo
    this.queryParams.itemId = itemIdFromRoute || null
    this.queryParams.receiptNoteNo = receiptNoteNoFromRoute || null
    this.queryParams.pageNum = 1
    this.getList()
  },
  // 当路由查询参数发生变化时（例如 itemId 或 receiptNoteNo 变化），更新过滤条件并重新加载
  beforeRouteUpdate(to, from, next) {
    const itemIdFromRoute = to && to.query && to.query.itemId
    const receiptNoteNoFromRoute = to && to.query && to.query.receiptNoteNo
    this.queryParams.itemId = itemIdFromRoute || null
    this.queryParams.receiptNoteNo = receiptNoteNoFromRoute || null
    this.queryParams.pageNum = 1
    this.getList()
    next()
  },
  methods: {
    /** 查询箱码列表列表 */
    getList() {
      this.loading = true
      listBarcode(this.queryParams).then(response => {
        let rows = Array.isArray(response.rows) ? response.rows : []
        // 兜底前端过滤：按收料通知单编码过滤
        const rn = this.queryParams && this.queryParams.receiptNoteNo ? String(this.queryParams.receiptNoteNo).trim() : ''
        if (rn) {
          rows = rows.filter(r => String(r.receiptNoteNo || '').trim() === rn)
        }
        // 前端兜底：按 createdTime 倒序排序，避免后端未生效时影响展示
        rows.sort((a, b) => {
          const at = a && a.createdTime ? new Date(a.createdTime).getTime() : 0
          const bt = b && b.createdTime ? new Date(b.createdTime).getTime() : 0
          return bt - at
        })
        this.barcodeList = rows
        this.total = rn ? rows.length : response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        barcodeId: null,
        barcode: null,
        barcodeStatus: null,
        itemId: null,
        orderNo: null,
        batchNo: null,
        inventoryCode: null,
        supplierCode: null,
        packQuantity: null,
        unitCode: null,
        deliveryNoteNo: null,
        deliveryTime: null,
        receiptNoteNo: null,
        receivedTime: null,
        inspectionPlanNo: null,
        inspectedTime: null,
        purchaseInNo: null,
        putawayTime: null,
        isRejected: null,
        qualityResult: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedTime: null,
        remark: null,
        delFlag: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      // 清除按行跳转的 itemId 与收料通知单过滤，并移除路由上的相关参数
      this.queryParams.itemId = null
      this.queryParams.receiptNoteNo = null
      if (this.$route && this.$route.query && (this.$route.query.itemId || this.$route.query.receiptNoteNo)) {
        this.$router.replace({ path: '/system/barcode' })
      }
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.barcodeId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加箱码列表"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const barcodeId = row.barcodeId || this.ids
      getBarcode(barcodeId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改箱码列表"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.barcodeId != null) {
            updateBarcode(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addBarcode(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const barcodeIds = row.barcodeId || this.ids
      this.$modal.confirm('是否确认删除箱码列表编号为"' + barcodeIds + '"的数据项？').then(function() {
        return delBarcode(barcodeIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 打印当前行箱码信息 */
    handlePrint(row) {
      const closeLoading = () => { try { this.$modal && this.$modal.closeLoading && this.$modal.closeLoading() } catch (e) {} }
      try { this.$modal && this.$modal.loading && this.$modal.loading('正在生成打印预览...') } catch (e) {}
      try {
        const invCode = row && row.inventoryCode ? String(row.inventoryCode) : ''
        const batchNo = row && row.batchNo ? String(row.batchNo) : ''
        const packQty = row && (row.packQuantity != null) ? String(row.packQuantity) : ''
        const invName = row && row.inventoryName ? String(row.inventoryName) : ''
        const supplierName = row && row.supplierName ? String(row.supplierName) : ''
        const deliveryDate = this.formatDate(row && row.deliveryTime)
        const barcodeText = row && row.barcode ? String(row.barcode) : ''
        const qrSrc = `https://api.qrserver.com/v1/create-qr-code/?size=160x160&data=${encodeURIComponent(barcodeText)}`

        const css = `
          *{box-sizing:border-box;}
          .print-card{width:820px;margin:0 auto;font-family:"Microsoft YaHei",Arial,sans-serif;color:#000;}
          .grid{display:grid;grid-template-columns:140px 300px 200px;grid-auto-rows:52px;border:1px solid #333;}
          .cell{border:1px solid #333;padding:8px 10px;font-size:16px;line-height:36px;}
          .label{font-weight:bold;background:#f9f9f9;}
          .qr{grid-row:1 / span 4;grid-column:3 / 4;display:flex;flex-direction:column;align-items:center;justify-content:center;}
          .qr img{width:160px;height:160px;}
          .qr .code-text{font-size:12px;color:#555;margin-top:6px;line-height:1;}
        `

        const html = `
          <div class="print-card">
            <div class="grid">
              <div class="cell label">存货编码</div><div class="cell">${invCode}</div><div class="cell qr"><img src="${qrSrc}" alt="QR"><div class="code-text">${barcodeText}</div></div>
              <div class="cell label">批次号</div><div class="cell">${batchNo}</div>
              <div class="cell label">装箱数量</div><div class="cell">${packQty}</div>
              <div class="cell label">存货名称</div><div class="cell">${invName}</div>
              <div class="cell label">供应商名称</div><div class="cell">${supplierName}</div><div class="cell"></div>
              <div class="cell label">发货日期</div><div class="cell">${deliveryDate}</div><div class="cell"></div>
            </div>
          </div>
        `

        const w = window.open('', '_blank')
        w.document.write(`<!doctype html><html><head><meta charset="utf-8"><title>箱码打印</title><style>${css}</style></head><body>${html}</body></html>`)
        w.document.close(); w.focus()
        setTimeout(() => { try { w.print(); w.close() } catch (e) {} }, 150)
      } finally {
        closeLoading()
      }
    },
    /** 简单日期格式化（YYYY-MM-DD），输入可为字符串或Date */
    formatDate(input) {
      if (!input) return ''
      try {
        const dt = (input instanceof Date) ? input : new Date(input)
        if (isNaN(dt.getTime())) return String(input).slice(0, 10)
        const y = dt.getFullYear(), m = ('0' + (dt.getMonth() + 1)).slice(-2), d = ('0' + dt.getDate()).slice(-2)
        return `${y}-${m}-${d}`
      } catch (e) {
        return String(input).slice(0, 10)
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/barcode/export', {
        ...this.queryParams
      }, `barcode_${new Date().getTime()}.xlsx`)
    },
    /** 表格序号计算 */
    computeIndex(index) {
      return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1
    }
  }
}
</script>
